package com.wgts.wgts.tools;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;

import com.wgts.wgts.control.statusBar.IsplayHelper;
import com.wgts.wgts.control.toast.MoHuToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.UUID;

import static com.wgts.wgts.AppConstant.SHARE_BITMAP_PATH;


public class Tools {

    private static final int HOUR_SECOND = 60 * 60;

    /**
     * 一分钟的秒数
     */
    private static final int MINUTE_SECOND = 60;

    public static String change(long second) {
        if (second <= 0) {

            return "00:00:00";
        }

        StringBuilder sb = new StringBuilder();
        long hours = second / HOUR_SECOND;
        if (hours > 0) {

            second -= hours * HOUR_SECOND;
        }

        long minutes = second / MINUTE_SECOND;
        if (minutes > 0) {

            second -= minutes * MINUTE_SECOND;
        }

        StringBuilder result = new StringBuilder();
        result.append(hours >= 10 ? (hours + "") : ("0" + hours));
        result.append(":");
        result.append(minutes >= 10 ? (minutes + "") : ("0" + minutes));
        result.append(":");
        result.append(second >= 10 ? (second + "") : ("0" + second));


        return result.toString();
    }


    public static ViewGroup.LayoutParams setViewMargin(View view, boolean isDp, int left, int right, int top, int bottom) {
        if (view == null) {
            return null;
        }

        int leftPx = left;
        int rightPx = right;
        int topPx = top;
        int bottomPx = bottom;
        ViewGroup.LayoutParams params = view.getLayoutParams();
        ViewGroup.MarginLayoutParams marginParams = null;
        //获取view的margin设置参数
        if (params instanceof ViewGroup.MarginLayoutParams) {
            marginParams = (ViewGroup.MarginLayoutParams) params;
        } else {
            //不存在时创建一个新的参数
            marginParams = new ViewGroup.MarginLayoutParams(params);
        }

        //根据DP与PX转换计算值
        if (isDp) {
            leftPx = IsplayHelper.dpToPx(left);
            rightPx = IsplayHelper.dpToPx(right);
            topPx = IsplayHelper.dpToPx(top);
            bottomPx = IsplayHelper.dpToPx(bottom);
        }
        //设置margin
        marginParams.setMargins(leftPx, topPx, rightPx, bottomPx);
        view.setLayoutParams(marginParams);
        return marginParams;
    }

    public static void setViewPadding(View view, boolean isDp, int left, int right, int top, int bottom) {


        int leftPx = left;
        int rightPx = right;
        int topPx = top;
        int bottomPx = bottom;

        //根据DP与PX转换计算值
        if (isDp) {
            leftPx = IsplayHelper.dpToPx(left);
            rightPx = IsplayHelper.dpToPx(right);
            topPx = IsplayHelper.dpToPx(top);
            bottomPx = IsplayHelper.dpToPx(bottom);
        }
        //设置margin

        view.setPadding(leftPx, topPx, rightPx, bottomPx);

    }


    public static void KeepBitmap(View view, Context context){
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        saveBitmap(context, bitmap);

    }


    /**
     * 保存bitmap到本地
     *
     * @param context
     * @param mBitmap
     * @return
     */
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SHARE_BITMAP_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()  +  File.separator + "DCIM" + File.separator + "Camera";
        }
        try {
            filePic = new File(savePath + File.separator + UUID.randomUUID().toString() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(filePic)));
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        MoHuToast.showToast("图片保存成功！");

        return filePic.getAbsolutePath();
    }

    public static DisplayMetrics metrics(Activity activity){

        DisplayMetrics outMetrics = new DisplayMetrics();
        if(activity != null){
            activity.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        }
        return outMetrics;
    }




    public static String shareCodePath(String qrCode, String Type, String shareId){
        JSONObject jsonObject = new JSONObject();
        try {
            if(AppInfor.getInstance().getUserState() > 1){
                jsonObject.put("userCode", AppInfor.getInstance().getInviteCode());
            }else{
                jsonObject.put("userCode", "null");
            }
            jsonObject.put("urlType", Type);
            jsonObject.put("seqNo", String.valueOf(System.currentTimeMillis()));
            if(shareId != null && !shareId.equals("")){
                jsonObject.put("shareId", shareId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }



        String sharePath = null;
        if(qrCode.contains("?")){
            sharePath = qrCode + "&" + "params=" + android.util.Base64.encodeToString(jsonObject.toString().replaceAll("[\\s*\t\n\r]", "").getBytes(), android.util.Base64.NO_WRAP);
        }else {
            sharePath = qrCode + "?" + "params=" + android.util.Base64.encodeToString(jsonObject.toString().replaceAll("[\\s*\t\n\r]", "").getBytes(), android.util.Base64.NO_WRAP);
        }


        return sharePath;
    }


//    public static String encoderMap(Map<String, Object> data) {
//        try {
//            String str = JsonUtil.toJSon(data);
//            String  result = new String(java.util.Base64.encodeBase64(str.getBytes("UTF-8")));
//            result = result.replaceAll("[\\s*\t\n\r]", "");
//            return URLEncoder.encode(result,"UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


    public static  void call(Context context) {
//        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+"4000518180"));
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(intent);
    }

    public static  void call(Context context, String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneNumber));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 粘贴复制
     */
    public static void CopyToClipboard(Context context,String text){
        ClipboardManager clipboardManager =
                (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        /**之前的应用过期的方法，clipboardManager.setText(copy);*/
        assert clipboardManager != null;
        clipboardManager.setPrimaryClip(ClipData.newPlainText(null,text));
        if (clipboardManager.hasPrimaryClip()){
            clipboardManager.getPrimaryClip().getItemAt(0).getText();
        }
    }


    /**
     * 检测当的网络（WLAN、3G/2G）状态
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


    public static boolean ping(String hostIp) throws IOException {

        Process process = Runtime.getRuntime().exec("ping " + hostIp);
        InputStreamReader r = new InputStreamReader(process.getInputStream());
        LineNumberReader returnData = new LineNumberReader(r);
        String returnMsg="";
        String line = "";
        while ((line = returnData.readLine()) != null) {
            System.out.println(line);
            returnMsg += line;
        }

        if(returnMsg.indexOf("100% loss")!=-1){
            System.out.println("与 " + hostIp +" 连接不畅通.");
            return false;
        }  else{
            System.out.println("与 " + hostIp +" 连接畅通.");
            return true;
        }


    }





}
